import { useState, useRef, useEffect } from 'react';
import {
  sendChatMessage,
  fetchSessionMessages,
  clearSessionMessages,
  cancelChatRequest,
} from '../services/api';
import Message from './Message';
import ChatSettings from './ChatSettings';
import McpManager from './McpManager';
import { loadSessionSettings, DEFAULT_SETTINGS } from '../utils/chatSettings';

/**
 * 聊天组件
 */
export default function Chat({ activeSessionId, userId }) {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [mcpOpen, setMcpOpen] = useState(false);
  const [sessionSettings, setSessionSettings] = useState(DEFAULT_SETTINGS);
  const settingsReloadKey = useRef(0);
  const messagesEndRef = useRef(null);
  const chatContainerRef = useRef(null);
  const abortRef = useRef(null);
  const requestIdRef = useRef(null);

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 加载会话历史
  useEffect(() => {
    const load = async () => {
      if (!activeSessionId) return;
      const s = loadSessionSettings(activeSessionId);
      setSessionSettings(s);
      try {
        const data = await fetchSessionMessages(activeSessionId, 1, 50);
        const list = (data.messages || []).map((m) => ({
          role: m.role?.toUpperCase() === 'ASSISTANT' ? 'ASSISTANT' : (m.role?.toUpperCase() === 'USER' ? 'USER' : 'ASSISTANT'),
          content: m.content || '',
        }));
        setMessages(list);
      } catch (e) {
        console.error(e);
      }
    };
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeSessionId, settingsReloadKey.current]);

  const handleSettingsChange = (cfg) => {
    setSessionSettings(cfg);
    settingsReloadKey.current += 1;
  };

  const generateRequestId = () => {
    try {
      if (typeof crypto !== 'undefined' && crypto.randomUUID) {
        return crypto.randomUUID();
      }
    } catch (e) {
      console.warn('生成 requestId 失败，使用兜底方案', e);
    }
    return `req-${Date.now()}-${Math.random().toString(16).slice(2)}`;
  };

  // 发送消息
  const handleSend = async () => {
    if (!inputValue.trim() || isLoading) return;

    const userMessage = inputValue.trim();
    setInputValue('');
    setIsLoading(true);

    // 为本次请求创建 AbortController
    const controller = new AbortController();
    abortRef.current = controller;

    const requestId = generateRequestId();
    requestIdRef.current = requestId;

    // 添加用户消息
    const newMessages = [...messages, { role: 'USER', content: userMessage }];
    setMessages(newMessages);

    // 添加占位的AI回复
    let assistantMessage = { role: 'ASSISTANT', content: '', isLoading: true };
    const finalMessages = [...newMessages, assistantMessage];
    setMessages(finalMessages);

    let accumulatedText = '';
    let toolResultMessages = []; // 存储工具结果消息

    try {
      await sendChatMessage(
        {
          query: userMessage,
          prompt: sessionSettings.prompt,
          imageUrls: sessionSettings.imageUrls || [],
          model: sessionSettings.model,
          temperature: sessionSettings.temperature,
          enableCoT: sessionSettings.enableCoT,
          cotMode: sessionSettings.cotMode,
          cotExample: sessionSettings.cotExample,
          chatMode: sessionSettings.chatMode,
          sessionId: activeSessionId,
          userId,
          showToolResults: sessionSettings.showToolResults,
          requestId,
        },
        {
          onChunk: (data) => {
            const finishReason = data.metadata?.finishReason;

            // 忽略工具调用消息 (TOOL_CALLS)，不展示
            if (finishReason === 'TOOL_CALLS') {
              return;
            }

            // 处理工具返回结果 (TOOL)
            if (finishReason === 'TOOL' && data.output?.metadata?.name) {
              toolResultMessages.push({
                role: 'ASSISTANT',
                content: '',
                toolResult: {
                  name: data.output.metadata.name,
                  result: data.output.text || '',
                },
                isLoading: false,
              });
              setMessages((prev) => {
                // 移除旧的占位消息，添加所有工具结果消息
                const withoutPlaceholder = prev.slice(0, -1);
                return [...withoutPlaceholder, ...toolResultMessages, assistantMessage];
              });
              return;
            }

            // 处理普通文本消息
            if (data.output?.text) {
              accumulatedText = accumulatedText || '';
              const newText = data.output.text;
              
              // 累加文本
              accumulatedText += newText;

              // 更新消息（有内容时不再显示思考动画）
              setMessages((prev) => {
                const updated = [...prev];
                const lastIndex = updated.length - 1;
                if (lastIndex >= 0 && updated[lastIndex].role === 'ASSISTANT') {
                  updated[lastIndex] = {
                    ...updated[lastIndex],
                    content: accumulatedText,
                    isLoading: false, // 有内容时停止思考动画
                  };
                }
                return updated;
              });
            }

            // 检查是否完成
            if (finishReason === 'STOP') {
              setIsLoading(false);
              setMessages((prev) => {
                const updated = [...prev];
                const lastIndex = updated.length - 1;
                if (lastIndex >= 0 && updated[lastIndex].role === 'ASSISTANT') {
                  updated[lastIndex] = {
                    ...updated[lastIndex],
                    isLoading: false,
                  };
                }
                return updated;
              });
            }
          },
          onComplete: () => {
            setIsLoading(false);
            abortRef.current = null;
            requestIdRef.current = null;
            setMessages((prev) => {
              const updated = [...prev];
              const lastIndex = updated.length - 1;
              if (lastIndex >= 0 && updated[lastIndex].role === 'ASSISTANT') {
                updated[lastIndex] = {
                  ...updated[lastIndex],
                  isLoading: false,
                };
              }
              return updated;
            });
          },
          onError: (error) => {
            setIsLoading(false);
            const isAbort = error && error.name === 'AbortError';
            if (!isAbort) {
              console.error('发送消息失败:', error);
            }
            abortRef.current = null;
            requestIdRef.current = null;
            // 若为主动中止，不提示
            if (isAbort) {
              setMessages((prev) => {
                const updated = [...prev];
                const lastIndex = updated.length - 1;
                if (lastIndex >= 0 && updated[lastIndex].role === 'ASSISTANT') {
                  updated[lastIndex] = {
                    ...updated[lastIndex],
                    isLoading: false,
                  };
                }
                return updated;
              });
              return;
            }
            alert('发送消息失败，请检查网络连接');
          },
          signal: controller.signal,
        }
      );
    } catch (error) {
      console.error('发送消息出错:', error);
      setIsLoading(false);
      abortRef.current = null;
      requestIdRef.current = null;
      alert('发送消息失败，请检查网络连接');
    }
  };

  const handleStop = async () => {
    if (!isLoading) return;
    const controller = abortRef.current;
    const requestId = requestIdRef.current;

    if (controller) {
      controller.abort();
    }

    abortRef.current = null;

    try {
      await cancelChatRequest({ requestId, sessionId: activeSessionId });
    } catch (error) {
      console.error('取消对话失败:', error);
    }
  };

  // 处理键盘事件
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <div className="chat-container">
      <div className="chat-header">
        <h1>AI 智能助手</h1>
        <p>会话管理、MCP服务管理功能待实现</p>
      </div>

      <div className="chat-messages" ref={chatContainerRef}>
        {messages.length === 0 && (
          <div className="empty-state">
            <p>开始与 AI 智能助手对话吧！</p>
          </div>
        )}
        {messages.map((message, index) => (
          <Message
            key={index}
            role={message.role}
            content={message.content}
            isLoading={message.isLoading}
            toolCalls={message.toolCalls}
            toolResult={message.toolResult}
          />
        ))}
        <div ref={messagesEndRef} />
      </div>

      <div className="chat-tools">
        <button className="tool-btn" onClick={()=>setSettingsOpen(true)}>设置</button>
        <button className="tool-btn" onClick={()=>setMcpOpen(true)}>MCP服务</button>
        <button
          className="tool-btn"
          disabled={!activeSessionId || isLoading}
          onClick={async () => {
            if (!activeSessionId) return;
            if (!confirm('确认清空该会话的聊天记录？')) return;
            try {
              await clearSessionMessages(activeSessionId);
              const data = await fetchSessionMessages(activeSessionId, 1, 50);
              const list = (data.messages || []).map((m) => ({
                role: m.role?.toUpperCase() === 'ASSISTANT' ? 'ASSISTANT' : (m.role?.toUpperCase() === 'USER' ? 'USER' : 'ASSISTANT'),
                content: m.content || '',
              }));
              setMessages(list);
            } catch (e) {
              console.error(e);
              alert('清空失败');
            }
          }}
        >清空会话</button>
      </div>

      <div className="chat-input-container">
        <textarea
          className="chat-input"
          placeholder="输入消息... (Shift+Enter换行，Enter发送)"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyPress={handleKeyPress}
          disabled={isLoading}
          rows={3}
        />
        {isLoading ? (
          <button
            type="button"
            className="stop-button"
            onClick={handleStop}
            disabled={!isLoading}
          >
            停止
          </button>
        ) : (
          <button
            type="button"
            className="send-button"
            onClick={handleSend}
            disabled={!inputValue.trim()}
          >
            发送
          </button>
        )}
      </div>
      <ChatSettings
        sessionId={activeSessionId}
        open={settingsOpen}
        onClose={()=>setSettingsOpen(false)}
        onChange={handleSettingsChange}
      />
      <McpManager
        open={mcpOpen}
        onClose={()=>setMcpOpen(false)}
      />
    </div>
  );
}

